package com.Redis.Controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.Redis.Enum.ReportType;
import com.Redis.Model.ReportCourse;
import com.Redis.Model.ReportData;
import com.Redis.Service.ReportServiceI;
import com.Redis.Utils.JedisUtil;
import com.Redis.Utils.MessageUtil;
import com.Redis.Utils.RedisPool;
import com.Redis.Utils.SerialoizebleUtil;
import com.Redis.Utils.SerialoizebleUtilbak;
import com.Redis.Utils.StringUtil;

@Controller
public class ReportController {
	private Logger logger = Logger.getLogger(this.getClass().getName());
	public static byte[] rediskey = "key".getBytes();
	public static byte[] dstkey = "dstkey".getBytes();
	public static long time = 0;

	@Autowired
	private ReportServiceI reportService;

	// 自动注入（spring 配合的线程池）
	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
		
	/**
	 * 生产消息
	 * 
	 * @throws InterruptedException
	 */
	@RequestMapping("/getReport")
	public void getReportData() throws InterruptedException {
		RedisPool.getJedis().flushAll(); //清空缓存
		
		getReportSingleData(); // 单次课程封装对象放入Redis消息队列
		getReportGroupData(); // 课组期中期末封装对象放入Redis消息队列				
		//发布一个频道 通知客户端可以消费消息了
		RedisPool.getJedis().publish("reportChannel","StartReport");      
	}
	/**
	 * 异步消费消息《test》
	 * @return 
	 * @return 
	 * 
	 * @throws InterruptedException
	 */
//	@RequestMapping("/outReport")
//	@ResponseBody
//	public void consumptionReportData() throws InterruptedException {
//		//启动消费者	
//		consumerServices.consumption();
//		logger.info("开始消费！！！！！");
//		System.err.println("200");
//	}
	/**
	 * 获取单次课的信息
	 * 
	 * @throws InterruptedException
	 */
	@SuppressWarnings("unused")
	private void getReportSingleData() {
		java.sql.Date dateTime = new java.sql.Date(new Date().getTime());

		List<ReportData> reportData = reportService.getReportDataByCourseId(dateTime);
		
		System.err.println("======单次课程的消息数量======"+reportData.size());
		
		for(int i = 0 ; i < reportData.size() ; i++) {
			logger.info(reportData.get(i).toString());
			try {
				MessageUtil msg = new MessageUtil();
				ReportData tmpReport = reportData.get(i);
				tmpReport.setReportType(ReportType.SINGLE.getIndex()); //单次
				msg.setReportData(reportData.get(i));
				logger.info(msg.toString());
				JedisUtil.lpush(rediskey, SerialoizebleUtil.serialize(msg));
			} catch (Exception e) {
				// TODO: handle exception
				e.getMessage();
			}
		}
		
	}

	/**
	 * 获取课组的信息
	 * 
	 * @return
	 * 
	 * @throws InterruptedException
	 */
	@SuppressWarnings("unused")
	private void getReportGroupData() {
		java.sql.Date dateTime = new java.sql.Date(new Date().getTime());
		List<ReportData> reportgroupData = reportService.getReportGroupInfo(dateTime);
		Iterator<ReportData> it = reportgroupData.iterator();

		while (it.hasNext()) {
			ReportData tmpReport = _isStatisticsByGroupId(it.next());
			logger.info("tmpReport"+tmpReport.toString());
			getCrouseStudentInfoByCourseGroupInfo(tmpReport);
		}	
	}

	private void getCrouseStudentInfoByCourseGroupInfo(ReportData reportData) {
		if (reportData.isMidStatistics()) { // 期中
			List<ReportData> reportMidData = reportService.getReportDataByGroupId(reportData.getMidStr());
			System.err.println("======期中消息数量======"+reportMidData.size());
			for(int i = 0 ; i < reportMidData.size() ; i++) {		
				try {
					MessageUtil msg = new MessageUtil();
					ReportData tmpReport = reportMidData.get(i);
					tmpReport.setCourseId(reportData.getMidStr());
					tmpReport.setGroupId(reportData.getGroupId());
					tmpReport.setReportType(ReportType.MID.getIndex());
					tmpReport.setSubjectId(reportData.getSubjectId());				
					msg.setReportData(tmpReport);				
					JedisUtil.lpush(rediskey, SerialoizebleUtil.serialize(msg)); // 放入 Redis消息队列
				} catch (Exception e) {
					// TODO: handle exception
					e.getMessage();
				}
			}
		
		}
		if (reportData.isEndStatistics()) { // 期末
			List<ReportData> reportEndData = reportService.getReportDataByGroupId(reportData.getEndStr());
			System.err.println("======期末消息数量======"+reportEndData.size());
			
			for(int i = 0 ; i < reportEndData.size() ; i++) {		
				try {
					ReportData tmpReport = reportEndData.get(i);
					MessageUtil msg = new MessageUtil();
					tmpReport.setCourseId(reportData.getEndStr());
					tmpReport.setGroupId(reportData.getGroupId());
					tmpReport.setReportType(ReportType.END.getIndex());
					tmpReport.setSubjectId(reportData.getSubjectId());				
					msg.setReportData(tmpReport);			
					JedisUtil.lpush(rediskey, SerialoizebleUtil.serialize(msg)); // 放入 Redis消息队列
				} catch (Exception e) {
					// TODO: handle exception
					e.getMessage();
				}
			}			
		}

	}	
	/**
	 * 得到此课组是否可以进行报告统计
	 * 
	 * @return
	 */
	private ReportData _isStatisticsByGroupId(ReportData reportData) {		
		java.sql.Date dateTime = new java.sql.Date(new Date().getTime());
		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("groupId", reportData.getGroupId());
		hashMap.put("dateTime", dateTime);
		List<ReportCourse> reportCourseData = reportService.getReportCourseInfo(hashMap);

		Iterator<ReportCourse> it = reportCourseData.iterator();
		StringBuilder sb = new StringBuilder();
		while (it.hasNext()) {
			sb.append(it.next().getCourseId() + ",");
		}
		if (reportData.getMidTerm() != 1) { // 设置期中可统计标识

			boolean isTrue = StringUtil.strCompareStr(sb.toString(), reportData.getMidStr(), reportData.getMidStr());
			if (isTrue) {
				reportData.setMidStatistics(true); // 期中可以统计
			}
		}
		if (reportData.getEndTerm() != 1) { // 设置期末可统计标识
			boolean isTrue = StringUtil.strCompareStr(sb.toString(), reportData.getEndStr(), reportData.getEndStr());
			if (isTrue) {
				reportData.setEndStatistics(true); // 期末可以统计
			}

		}
		
		return reportData;

	}
}
